package keter.web.controller;

import java.util.Date;

import keter.framework.web.util.MediaType;
import keter.model.User;
import keter.web.controller.base.KeterBaseController;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/regist")
@RestController
public class RegistController extends KeterBaseController {

    private static final Logger logger = LoggerFactory.getLogger(RegistController.class);

    public RegistController() {
    }
    
//    /**
//     * <p>Method ：add
//     * <p>Description : 
//     *
//     * @param model
//     * @return 
//     * @author  顾力行-gulixing@msn.com
//     */
//    //,HttpServletResponse response
//    @RequestMapping(value="/regist.ajax", method = RequestMethod.POST,consumes = MediaType.APPLICATION_JSON)
//    public Map<String, String> ajaxregist(HttpServletRequest request) {
//        Map<String, String> map = getSuccessMap();
//        User user = new User().fromJson(RequestUtil.getJson(request));
//        if(!UserService.service.saveWithDefaultRole(user)){ 
//            map = getErrorMap("用户账号["+user.getStr("username")+"]已存在，请使用其他名称进行注册！");
//        }
//        return map;
//    }
     
    /**
     * <p>Method ：add
     * <p>Description : 
     *
     * @param model
     * @return 
     * @author  顾力行-gulixing@msn.com
     */
    @RequestMapping(value=Routes.Index, method = RequestMethod.POST, produces = MediaType.JSON)// 
    public String regist(
    		@RequestParam(value="username")String username,
    		@RequestParam(value="name")String name,
    		@RequestParam(value="password")String password,
    		@RequestParam(value="email",required=false)String email
    	) {
//    	Map<String, String> map = success();
    	User user = new User()
    	.set("name",name)
		.set("username",username)
		.set("password",password)
		.set("email",email)
		.set("created", new Date());
        //保存用户并对其添加默认角色(USER)，否则新用户将无法直接登录系统
        //其他(在无需变更用户角色对应关系)情况下可以考虑使用save()方法
    	if(!User.service.saveWithDefaultRole(user)){	
    		return error("用户账号["+user.getStr("username")+"]已存在，请使用其他名称进行注册！");
    	}
        return success();
    }
    
    /**
     * <p>Method ：add
     * <p>Description : 进入注册页面
     *
     * @param model
     * @return 
     * @author  顾力行-gulixing@msn.com
     */
    @Deprecated
    @RequestMapping(value = Routes.Index, method = RequestMethod.GET)
    public ModelAndView index() {
        return  new ModelAndView("regist/regist_index");
    }

}